<?php
/**
 * 权限相关配置
 * @since   2018-02-06
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace app\backstage\controller;


use app\model\FreshAdminAuthGroup;
use app\model\FreshAdminAuthGroupAccess;
use app\model\FreshAdminAuthRule;
use app\model\FreshAdminMenu;
use app\util\ReturnCode;
use app\util\Tools;

class Auth extends Base {

    /**
     * 获取权限组列表
     */
    public function index() {

        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $status = $this->request->get('status', '');
        $platformID = $this->request->get('platformID', '');
        $isOp = $this->request->get('isOp', '');
        $isService = $this->request->get('isService', '');
        $where = [];
        if($keywords)
            $where['a.name'] = ['like', "%{$keywords}%"];
        if ($status != '') {
            $where['a.status'] = $status;
        }
        if($platformID != ''){
            $where['a.platformID'] = $platformID;
        }
        if($isOp != ''){
            $where['a.isOp'] = $isOp;
        }
        if($isService != ''){
            $where['a.isService'] = $isService;
        }
        $uplatID = $this->userPlatform();
        if($uplatID){
            $where['a.platformID'] = $uplatID;
        }
        $listObj = (new FreshAdminAuthGroup())->alias('a')
            ->field('a.*,p.name as platformName')
            ->join('platform p', 'p.id=a.platformID', 'left')
            ->where($where)
            ->order('a.id DESC')
            ->paginate($limit, false, ['page' => $start])->toArray();
        foreach($listObj['data'] as $key => $var){
            $listObj['data'][$key]['isOpName'] = $var['isOp'] == 1 ? '是':'否';
            $listObj['data'][$key]['isServiceName'] = $var['isService'] == 1 ? '是':'否';
            $listObj['data'][$key]['statusName'] = $var['status'] == 1 ? '正常':'禁用';
        }
        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    /**
     * 获取全部已开放的可选组
     */
    public function getGroups() {
        $listInfo = (new FreshAdminAuthGroup())->where(['status' => 1])->order('id', 'DESC')->select();
        $count = count($listInfo);
        $listInfo = Tools::buildArrFromObj($listInfo);

        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $count
        ]);
    }

    /**
     * 获取组所在权限列表
     */
    public function getRuleList() {
        $groupId = $this->request->get('groupId', 0);

        $list = (new FreshAdminMenu)->where([])->order('sort', 'ASC')->select();
        $list = Tools::buildArrFromObj($list);
        $list = listToTree($list);

        $rules = [];
        if ($groupId) {
            $rules = (new FreshAdminAuthRule())->where(['groupId' => $groupId])->select();
            $rules = Tools::buildArrFromObj($rules);
            $rules = array_column($rules, 'url');
        }
        $newList = $this->buildList($list, $rules);

        return $this->buildSuccess([
            'list' => $newList
        ]);
    }

    /**
     * 新增组
     */
    public function add() {
        $rules = [];
        $postData = $this->request->post();
        if (isset($postData['rules']) && $postData['rules']) {
            $rules = $postData['rules'];
            $rules = array_filter($rules);
        }
        unset($postData['rules']);
        if(!isset($postData['isOp']) || empty($postData['isOp'])){
            $postData['isOp'] = 2;
        }
        if(!isset($postData['isService']) || empty($postData['isService'])){
            $postData['isService'] = 2;
        }
        if(isset($postData['isOp']) && $postData['isOp'] && isset($postData['isService']) && $postData['isService']){
            if($postData['isService'] == $postData['isOp'] && $postData['isOp'] != 2){
                return $this->buildFailed(ReturnCode::INVALID, '操作员和客服员冲突');
            }
        }
        $platformID = $this->userPlatform();
        if(empty($platformID) && (!isset($postData['platformID']) || empty($postData['platformID']))){
            return $this->buildFailed(ReturnCode::INVALID, '请选择平台');
        }
        if(!isset($postData['name']) || empty($postData['name'])){
            return $this->buildFailed(ReturnCode::INVALID, '请填写平台名称');
        }
        if(!isset($postData['description']) || empty($postData['description'])){
            $postData['description'] = '';
        }
        $data = [
            'isOp' => $postData['isOp'],
            'isService' => $postData['isService'],
            'platformID' => $platformID ? $platformID : $postData['platformID'],
            'name' => $postData['name'],
            'description' => $postData['description']
        ];
        $res = FreshAdminAuthGroup::create($data);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            if ($rules) {
                $insertData = [];
                foreach ($rules as $value) {
                    if ($value) {
                        $insertData[] = [
                            'groupId' => $res->id,
                            'url'     => $value
                        ];
                    }
                }
                (new FreshAdminAuthRule())->saveAll($insertData);
            }

            return $this->buildSuccess([]);
        }
    }

    /**
     * 权限组状态编辑
     */
    public function changeStatus() {
        $id = $this->request->get('id');
        $status = $this->request->get('status');

        $group = FreshAdminAuthGroupAccess::alias('a')
        ->field('a.uid,a.groupId,g.platformID,g.isOp')
        ->join('fresh_admin_auth_group g', 'a.groupId=g.id', 'left')
        ->join('fresh_admin_user u', 'a.uid=u.id', 'left')
        ->where('a.groupId', $id)
        ->where('u.status', 1)
        ->find();
        if($status == 0 && $group && $group['isOp'] == 1){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作组存在下属成员无法禁用');
        }
        $platformID = $this->userPlatform();
        if($platformID && $group['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::INVALID, '不能跨平台操作组');
        }
        $res = FreshAdminAuthGroup::update([
            'id'     => $id,
            'status' => $status
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 编辑用户
     */
    public function edit() {
        $postData = $this->request->post();
        if (isset($postData['rules']) && $postData['rules']) {
            $this->editRule();
        }
        unset($postData['rules']);
        if(!isset($postData['id']) || empty($postData['id'])){
            return $this->buildFailed(ReturnCode::INVALID, 'id为空');
        }
        if(!isset($postData['name']) || empty($postData['name'])){
            return $this->buildFailed(ReturnCode::INVALID, '请填写平台名称');
        }
        if(!isset($postData['description']) || empty($postData['description'])){
            $postData['description'] = '';
        }
        $group = FreshAdminAuthGroup::where('id', $postData['id'])->find();
        if(empty($group)) return $this->buildFailed(ReturnCode::INVALID, '用户组不存在');
        $platformID = $this->userPlatform();
        if($platformID && $group['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::INVALID, '不能跨平台操作组');
        }
        $data = [
            'id' => $postData['id'],
            'name' => $postData['name'],
            'description' => $postData['description']
        ];
        $res = FreshAdminAuthGroup::update($data);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 删除组
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }

        $group = FreshAdminAuthGroupAccess::alias('a')
        ->field('a.uid,a.groupId,g.platformID,g.isOp')
        ->join('fresh_admin_auth_group g', 'a.groupId=g.id', 'left')
        ->join('fresh_admin_user u', 'a.uid=u.id', 'left')
        ->where('a.groupId', $id)
        ->where('u.status', 1)
        ->find();
        if($group && $group['isOp'] == 1){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作组存在下属成员无法删除');
        }
        $platformID = $this->userPlatform();
        if($platformID && $group['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::INVALID, '不能跨平台操作组');
        }
        (new FreshAdminAuthGroupAccess())->where(['groupId' => $id])->delete();
        FreshAdminAuthGroup::destroy($id);
        FreshAdminAuthRule::destroy(['groupId' => $id]);

        return $this->buildSuccess([]);
    }

    /**
     * 从指定组中删除指定用户
     */
    public function delMember() {
        $gid = $this->request->get('gid', 0);
        $uid = $this->request->get('uid', 0);
        if (!$gid || !$uid) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $user = FreshAdminAuthGroupAccess::alias('a')
        ->field('a.uid,a.groupId,g.platformID,g.isOp')
        ->join('fresh_admin_auth_group g', 'a.groupId=g.id', 'left')
        ->where('a.uid', $uid)
        ->find();
        $platformID = $this->userPlatform();
        if($platformID && $user['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::INVALID, '不能跨平台操作组用户');
        }
        if($user['isOp'] == 1){
            \app\model\TaskRecord::where('opMid', $uid)->update(['status' => 2]);
            $list = \app\model\UserAllot::where('opMid', $uid)->field('userID')->select()->toArray();
            if($list){
                $userIds = array_column($list, 'userID');
                \app\model\User::where('userID', 'in', $userIds)->update(['isAllot' => 9]);
                \app\model\UserAllot::where('opMid', $uid)->update(['status' => 9]);
            }
        }
        $res = FreshAdminAuthGroupAccess::get(['uid' => $uid])->delete();
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 构建适用前端的权限数据
     */
    private function buildList($list, $rules) {
        $newList = [];
        foreach ($list as $key => $value) {
            $newList[$key]['title'] = $value['name'];
            $newList[$key]['key'] = $value['url'];
            if (isset($value['_child'])) {
                $newList[$key]['expand'] = true;
                $newList[$key]['children'] = $this->buildList($value['_child'], $rules);
            } else {
                if (in_array($value['url'], $rules)) {
                    $newList[$key]['checked'] = true;
                }
            }
        }

        return $newList;
    }

    /**
     * 编辑权限细节
     */
    private function editRule() {
        $postData = $this->request->post();
        $needAdd = [];
        $has = (new FreshAdminAuthRule())->where(['groupId' => $postData['id']])->select();
        $has = Tools::buildArrFromObj($has);
        $hasRule = array_column($has, 'url');
        $needDel = array_flip($hasRule);
        foreach ($postData['rules'] as $key => $value) {
            if (!empty($value)) {
                if (!in_array($value, $hasRule)) {
                    $data['url'] = $value;
                    $data['groupId'] = $postData['id'];
                    $needAdd[] = $data;
                } else {
                    unset($needDel[$value]);
                }
            }
        }
        if (count($needAdd)) {
            (new FreshAdminAuthRule())->saveAll($needAdd);
        }
        if (count($needDel)) {
            $urlArr = array_keys($needDel);
            FreshAdminAuthRule::destroy([
                'groupId' => $postData['id'],
                'url'     => ['in', $urlArr]
            ]);
        }
    }

}
